import axios from "axios";
import store from "@/store";

const instance = axios.create({
  baseURL: "http://127.0.0.1:10010",
  timeout: 3000,
  headers: { "X-Custom-Header": "foobar" },
});
import { mock } from "mockjs";
import router from "@/router";

mock(/^http:\/\/127\.0\.0\.1:10010\/calculate\/teacher\/page\?.*$/, "get", {
  data: {
    code: 1,
    "records|10": [
      {
        "id|+1": 10001,
        name: "@cname",
        "role|1": ["教师岗", "实验岗", "工勤岗", "管理岗", "双肩挑", "非学院双肩挑"],
        "level|1": ["四级", "五级", "六级", "七级", "八级", "九级", "十级", "十一级"],
        "profession|1": [
          "正高二级",
          "正高三级",
          "正高四级",
          "副高五级",
          "副高六级",
          "副高七级",
          "中级八级",
          "中级九级",
          "中级十级",
          "初级十一级",
          "初级十二级",
          "新进博士",
          "新进硕士",
          "见习",
        ],
        "workYear|0-5": 1,
        "managerPro|1": [
          "正校级",
          "副校级",
          "正处级",
          "副处级",
          "正科级",
          "副科级",
          "科员",
          "办事员",
          "见习",
        ],
        "managerYear|1-10": 1,
        "classHour|1-5": 2,
        "sciHour|1-5": 2,
        "publicService|1500-4000": 2300,
        "otherSalary|1": [0, 1],
        "isRetirement|1": [0, 1],
        "isGood|1": [0, 1],
        "isFit|1": [0, 1],
        "esScore|50-100": 83,
        "effectiveTime|5-15": 9,
        "overHour|1-5": 2,
        "score|200-400": 265,
        "bonus|15000-40000": 23000,
      },
    ],
    msg: "成功",
  },
});

// mock("http://127.0.0.1:10010/user/login", {
//   code: 1,
//   "data|4": {
//     username: "@cname",
//     token: "@guid",
//   },
//   msg: "登录成功",
// });

// mock("http://127.0.0.1:10010/calculate/teacher/sum", {
//   code: 1,
//   "data|20-100": 20,
//   msg: "成功",
// });

// mock(/^http:\/\/127.0.0.1:10010\/calculate\/teacher\/core?.*$/, {
//   code: 1,
//   msg: "计算成功",
// });

// mock(/^http:\/\/127.0.0.1:10010\/calculate\/teacher\/add?.*$/, {
//   code: 1,
//   msg: "添加成功",
// });

// mock(/^http:\/\/127.0.0.1:10010\/calculate\/teacher?.*$/, {
//   code: 1,
//   msg: "修改成功",
// });


// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const token = store.state.login.userinfo.token;
    if (token) {
      config.headers["authorization"] = token;
    }
    return config;
  },
  function (error) {
    const { response } = error;

    // 检查是否为401未授权错误
    if (response && response.status === 401) {
      store.commit("login/clearUserInfo");
      router.push("/login");
      return Promise.reject(new Error("登录过期，中断请求"));
    }

    // 其他错误直接抛给上层处理
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default instance;
